package com.ruge.common.shiro;

import com.ruge.system.pojo.entity.SysMenu;
import com.ruge.system.pojo.entity.SysRole;
import com.ruge.system.pojo.entity.SysUser;
import com.ruge.system.service.SysMenuService;
import com.ruge.system.service.SysRoleService;
import com.ruge.system.service.SysUserService;
import com.ruge.system.pojo.vo.ActiveUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 创建人 ：爱丽丝、如歌
 * 创建时间 ：2020-03-05  9:19
 * 描述 ：
 * @author dell
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysMenuService sysMenuService;
    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        ActiveUser activeUser= (ActiveUser) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(activeUser.getRoles().stream().map(SysRole::getName).collect(Collectors.toSet()));
        info.setStringPermissions(activeUser.getPermissions().stream().map(SysMenu::getTitle).collect(Collectors.toSet()));
        return info;
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (token.getPrincipal() == null) {
            return null;
        }
        //获取用户信息
        String loginName = token.getPrincipal().toString();
        SysUser sysUser = sysUserService.findByLoginName(loginName);
        //用户是否存在
        if (sysUser == null) {
            throw new UnknownAccountException();
        }
        ActiveUser activeUser=new ActiveUser();
        activeUser.setUser(sysUser);

        List<SysRole> sysRoles = sysRoleService.findRolesByUserId(sysUser.getId());
        List<SysMenu> sysMenus = new ArrayList<>();
        for (SysRole e : sysRoles) {
            sysMenus.addAll(sysMenuService.findAllBySysRole_Id(e.getId()));
        }
        activeUser.setRoles(new HashSet<>(sysRoles));
        activeUser.setPermissions(new HashSet<>(sysMenus));
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                activeUser,
                sysUser.getPassword(),
                null,
                getName()
        );
        return authenticationInfo;
    }
}
